import AccreditDia from '@/components/accreditDia/AccreditDia'
import ListEmptyNone from '@/components/antd-comp/empty/emptyNone'
import { showMessage } from '@/components/antd-comp/message'
import FouterPage from '@/components/fouter-page'
import { useDictStore } from '@/store/dictStore'
import { useRouteStoreHook } from '@/store/routeStore'
import { useTable } from '@/util/hook'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { Modal } from 'antd'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { callWordDel, callWordList } from './API'
import CreateModal from './components/callDialog'
import CallCont from './components/cont'
import CallTableHead from './components/tableHead'
import './css/styles.css'

import NoPermissionTem from '@/components/antd-comp/NoPermission'
import { Func } from '@/permissions/constants'
import { useFuncsStore } from '@/store/funcStore'
import { useBuriedEvent } from '@/util/buried'
import { captureAndAlertRequestErrorHoc } from '../../controllers/request'

const { confirm } = Modal

export default function CallWord() {
  // ------埋点------
  const { callWordBuriedEvent } = useBuriedEvent()
  const { t } = useTranslation()
  /**
   * 涉及顶部路由信息，在对应页面进行处理
   */
  const routeNames = [t('menu.callWord')]
  useRouteStoreHook(routeNames)

  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()

  const [open, setOpen] = useState(false)
  const [obj, setObj] = useState(null)
  /* 筛选 */
  const [searchName, setSearchName] = useState('')
  const [num, setNum] = useState('')
  /* tableList */
  const {
    page,
    pageSize,
    data: datalist,
    total,
    loading,
    setPage,
    search,
    reload
  } = useTable(
    {
      pageSize: 12,
    },
    param => callWordList(param.page, 12, searchName, num || ''),
    true,
    () => hasFuncPermission([Func.prompt.query])
  )

  /* 删除 */
  const handleDelete = id => {
    callWordBuriedEvent({
      event_name: '【删除】提示词按钮',
      data_id: id || null
    })
    // 删除权限限制
    if (!hasFuncPermission([Func.prompt.del])) {
      return
    }
    confirm({
      title: t('prompt'),
      icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
      content: t('call.callDelTitle'),
      okText: t('delete'),
      okType: 'danger',
      cancelText: t('cancel'),
      autoFocusButton: null,
      centered: true,
      destroyOnClose: true,
      onOk() {
        captureAndAlertRequestErrorHoc(
          callWordDel({ id })
            .then(res => {
              callWordBuriedEvent({
                page: '提示词页面',
                event_name: '确定【删除】提示词按钮',
                data_id: id || null,
                detail: JSON.stringify({ 结果: '成功' })
              })
              reload()
              showMessage({
                content: '删除成功',
                type: 'success'
              })
            })
            .catch(() => {
              callWordBuriedEvent({
                page: '提示词页面',
                event_name: '确定【删除】提示词按钮',
                data_id: id || null,
                detail: JSON.stringify({ 结果: '失败' })
              })
            })
        )
      }
    })
  }
  // 类型列表
  const [SearchList, setSearchList] = useState([])
  const [SearchListDialog, setSearchListDialog] = useState([])
  const { loadDictOptions } = useDictStore()
  const loadTypeList = (type = 'category') => {
    loadDictOptions(type).then((res: any) => {
      const list = [...res]
      setSearchListDialog(list)
      res.unshift({
        id: 0,
        label: '全部类型',
        value: 'all'
      })
      setSearchList(res)
      setNum(res[0].id)
    })
  }
  /* 初始化类别列表 */
  useEffect(() => {
    //loadTypeList()
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    const _page = window.LibPage
    if (_page) {
      setPage(_page)
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      delete window.LibPage
    } else {
      setPage(1)
    }
  }, [])
  /* 新增 编辑 */
  const diaEdit = (e: any) => {
    callWordBuriedEvent({
      event_name: e?.id ? '【编辑】提示词按钮' : '【创建】提示词按钮',
      data_id: e?.id || null
    })
    // 创建权限限制
    if (!e?.id && !hasFuncPermission([Func.prompt.add])) {
      return
    }
    // 编辑权限限制
    if (e?.id && !hasFuncPermission([Func.prompt.edit])) {
      return
    }
    setObj({
      ...e
      // optimizeBtnHid: e?.id ? true : false
    })
    setOpen(true)
  }
  /* 提交 */
  const submitData = () => {
    reload()
  }
  /* 搜索 */
  const seleCarFun = (e, id) => {
    setNum(e.id)
    search(e.id)

    callWordBuriedEvent({
      event_name: '搜索条件',
      detail: JSON.stringify({ 搜索条件: searchName, 类型: e.id })
    })
  }
  const SearchNameFun = e => {
    setSearchName(e)
    search(e)
    callWordBuriedEvent({
      event_name: '搜索条件',
      detail: JSON.stringify({ 搜索条件: e, 类型: num })
    })
  }
  /* 权限 */
  const [accredit, setAccredit] = useState(false)

  if (!hasFuncPermission([Func.prompt.menu], false)) {
    return <NoPermissionTem />
  }
  return (
    <div className="relative h-full" style={{ background: '#F5F7FB' }}>
      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      {/* 头部 */}
      <div className="flexRowStart px-10 py-5">
        <CallTableHead
          num={num}
          SearchList={SearchList}
          seleCarFun={seleCarFun}
          diaEdit={diaEdit}
          setSearchName={SearchNameFun}
        ></CallTableHead>
      </div>
      <div className=" relative top-[0] h-[calc(100vh-170px)] max-h-[calc(100vh-170px)] overflow-y-scroll pl-[40px] pr-[24px] scrollbar-hide">
        {/* 内容 */}
        {!loading && !datalist?.length ? (
          <ListEmptyNone style={{ background: '#F5F7FB' }} />
        ) : (
          <CallCont
            datalist={datalist}
            SearchList={SearchList}
            handleDelete={handleDelete}
            diaEdit={diaEdit}
            onAccreditDia={() => {
              setAccredit(true)
            }}
          ></CallCont>
        )}
      </div>
      {/* footer */}
      {!loading && datalist?.length > 0 && (
        <FouterPage page={page} pageSize={pageSize} total={total} setPage={newPage => setPage(newPage)}></FouterPage>
      )}

      {/* 弹窗 */}
      {open ? (
        <CreateModal
          submitData={submitData}
          datalist={SearchListDialog}
          open={open}
          setOpen={setOpen}
          obj={obj}
        ></CreateModal>
      ) : null}
      {/* 分配权限 */}
      {accredit && (
        <AccreditDia
          cancel={() => {
            setAccredit(false)
          }}
          submit={() => {
            setAccredit(false)
          }}
        />
      )}
    </div>
  )
}
